import fs from 'fs';
import path from 'path';
import pool from '../config/database';

async function initDatabase() {
  try {
    const sql = fs.readFileSync(
      path.join(__dirname, 'migrations', 'init.sql'),
      'utf-8'
    );

    const connection = await pool.getConnection();
    
    try {
      // 按分号分割SQL语句
      const statements = sql
        .split(';')
        .filter(statement => statement.trim().length > 0);

      // 依次执行每个SQL语句
      for (const statement of statements) {
        await connection.query(statement);
      }

      console.log('数据库初始化成功');
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('数据库初始化失败:', error);
    throw error;
  }
}

// 如果这个文件被直接运行
if (require.main === module) {
  initDatabase()
    .then(() => process.exit(0))
    .catch(() => process.exit(1));
}

export default initDatabase; 